﻿using UnityEditor;
using System.IO;
using System.Collections.Generic;
using UnityEngine;

public class ChangeAssetsName
{
    [MenuItem("BToolkit/混淆/改变所有资源文件名", false, -900)]
    private static void ChangeAllAssetsName()
    {
        string dir = EditorUtility.OpenFolderPanel("指定目录", "Assets", "");

        if (!EditorUtility.DisplayDialog("提示", $"确定修改目录\n\n{dir}\n\n下的所有文件名吗？该操作不可逆", "确定")) return;

        List<string> filePaths = new List<string>();
        filePaths.AddRange(Directory.GetFiles(dir, "*jpg", SearchOption.AllDirectories));
        filePaths.AddRange(Directory.GetFiles(dir, "*png", SearchOption.AllDirectories));

        int total = filePaths.Count;
        for (int i = 0; i < total; i++)
        {
            if (filePaths[i].Replace("\\", "/").Contains("/Fonts/")) continue;
            if (!ChangeOneAssetName(filePaths[i])) return;
            EditorUtility.DisplayProgressBar("改变资源名", "进度: " + (i + 1) + "/" + total, (i + 1) / (float)total);
        }
        EditorUtility.ClearProgressBar();

        Debug.Log($"全部资源({total}个)改变文件名完成");
        EditorUtility.DisplayDialog("标题", $"全部资源({total}个)改变文件名完成", "确定");
    }

    private static bool ChangeOneAssetName(string path)
    {
        if (!path.Contains(Application.dataPath))
        {
            Debug.LogError("不能选择Asset外的目录");
            return false;
        }
        path = path.Replace(Application.dataPath, "Assets").Replace("\\", "/");
        string fileName = Path.GetFileNameWithoutExtension(path);
        string extension = Path.GetExtension(path);

        string result = AssetDatabase.RenameAsset(path, fileName + "_2" + extension);
        if (!string.IsNullOrEmpty(result))
        {
            Debug.LogError(result);
        }

        AssetDatabase.Refresh();
        return true;
    }
}
